<script setup>

import {onMounted, reactive, ref, toRefs} from "vue";
import {userAdd, userUpdate} from "../../api/user.js";
import {ElMessage} from "element-plus";

const emit = defineEmits(['close'])

const props = defineProps({
  loadData: {},
  isUpdate: {
    type: Boolean,
    default: false
  }
})

const formRef = ref()
const loading = ref(false);
const data = reactive({
  formData: {
    username: '',
    qq: '',
    address: '',
  }
})

//校验
const rules = reactive({
  username: [
    {required: true, message: '请输入用户名', trigger: 'blur'},
  ],
  qq: [
    {required: true, message: '请输入QQ', trigger: 'blur'},
  ],
  address: [
    {required: true, message: '请输入住址', trigger: 'blur'},
  ]
})

const clear = () => {
  formRef.value.resetFields();
}

const submit = () => {
  formRef.value.validate((valid) => {
    if (!valid){
      return;
    }
    loading.value = true;
    if (props.isUpdate){
      userUpdate(data.formData).then(response => {
        ElMessage.success(response.data.message);
        loading.value = false;
        emit('close');
      })
    }else{
      userAdd(data.formData).then(response => {
        ElMessage.success(response.data.message);
        loading.value = false;
        emit('close');
      })
    }
  })
}

onMounted(() => {
  if (props.isUpdate) {
    data.formData = {...props.loadData}
  }
})

const {formData} = toRefs(data)
</script>

<template>
  <el-form :model="formData" ref="formRef" label-width="auto" style="max-width: 480px" class="user-form"
           :rules="rules" v-loading="loading">
    <el-form-item prop="username" label="用户名">
      <el-input v-model="formData.username"/>
    </el-form-item>
    <el-form-item prop="qq" label="QQ号">
      <el-input v-model="formData.qq"/>
    </el-form-item>
    <el-form-item prop="address" label="住址">
      <el-input v-model="formData.address"/>
    </el-form-item>
    <div class="dialog-footer" style="text-align:center">
      <el-button @click="clear">清空</el-button>
      <el-button type="primary" @click="submit">
        保存
      </el-button>
    </div>
  </el-form>
</template>

<style scoped>
.user-form {
  margin: 0 auto;
}
</style>